package com.tledu.student_manager.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tledu.student_manager.dao.UserDao;
import com.tledu.student_manager.exception.CustomException;
import com.tledu.student_manager.model.User;
import com.tledu.student_manager.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet(urlPatterns = "/login")
public class LoginServlet extends HttpServlet {
    private UserService userService;

    @Override
    public void init() throws ServletException {
        super.init();
        this.userService = new UserService(new UserDao());
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 登录的业务逻辑
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        // 校验内容
        try {
            User user = this.userService.login(username, password);
            // 登录成功
            HttpSession session = req.getSession();
            session.setAttribute("loginUser", user);
            // 登录成功访问首页
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code", 200);
            jsonObject.put("success", true);
            jsonObject.put("msg", "登录成功");
            jsonObject.put("data", user);
            resp.setContentType("application/json;charset=utf-8");
            resp.getWriter().println(jsonObject.toJSONString());
        } catch (CustomException e) {
            // 报错的响应
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code", 500);
            jsonObject.put("success", false);
            jsonObject.put("msg", e.getMessage());
            resp.setContentType("application/json;charset=utf-8");
            resp.getWriter().println(jsonObject.toJSONString());
        }
    }
}
